package charpter13.lynx;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Nineteen {
	public static void main(String[] args) {
		if (args.length != 1){
			System.out.println("Usage: java Nineteen file");
			System.exit(0);
		}
		
		Pattern p;
		Matcher m;
		StringBuffer sb = deleteStrings(args[0]);
		
		sb = deleteComments(sb);
		
		p = Pattern.compile("([A-Z][a-zA-Z]*?)[.| |\\(]");
		
		m = p.matcher(sb);
		
		Set<String> set = new HashSet<String>();
		
		while (m.find()) {
			set.add(m.group(1));
		}
		
		System.out.println(new ArrayList<String>(set));
		
	}

	private static StringBuffer deleteStrings(String filename) {
		Pattern p = Pattern.compile("\"(.*?)\"");
		
		Matcher m = p.matcher(read(filename));
		
		StringBuffer sb = new StringBuffer();
		
		while (m.find()) {
			m.appendReplacement(sb, "\"\"");
		}
		m.appendTail(sb);
		return sb;
	}

	private static StringBuffer deleteComments(StringBuffer sb) {
		Pattern p;
		Matcher m;
		p = Pattern.compile("/\\*.*?\\*/|//.*?(?=\n)",Pattern.DOTALL);
		
		m = p.matcher(sb);
		
		sb = new StringBuffer();
		
		while (m.find()) {
			m.appendReplacement(sb, "");
		}
		m.appendTail(sb);
		return sb;
	}
	
	public static String read(String fileName) {
	    StringBuilder sb = new StringBuilder();
	    try {
	      BufferedReader in= new BufferedReader(new FileReader(
	        new File(fileName).getAbsoluteFile()));
	      try {
	        String s;
	        while((s = in.readLine()) != null) {
	          sb.append(s);
	          sb.append("\n");
	        }
	      } finally {
	        in.close();
	      }
	    } catch(IOException e) {
	      throw new RuntimeException(e);
	    }
		return sb.toString();
	}
}
